package com.example.demo02.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo02.common.Result;
import com.example.demo02.entity.Orders;
import com.example.demo02.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
@CrossOrigin
public class OrdersController {

    @Autowired
    OrdersService ordersService;





    @PostMapping("/add")
    public Result add(@RequestBody Orders orders) {
        try {
            Integer orderId = ordersService.createOrder(orders);
            return Result.success(orderId); // 直接返回订单 ID
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("插入数据库错误");
            } else {
                return Result.error("系统错误");
            }
        }
    }


    @PutMapping("/update")
    public Result update(@RequestBody Orders orders) {
        ordersService.updateById(orders);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        ordersService.removeById(id);
        return Result.success();
    }

    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        ordersService.removeByIds(ids);
        return Result.success();
    }


    //根据orders表中的orderId查询订单详情

    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Orders> ordersList = ordersService.list();
        return Result.success(ordersList);
    }


    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Orders orders = ordersService.getById(id);
        return Result.success(orders);
    }

    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(required = false) Integer customerId) {
        Page<Orders> page = new Page<>(pageNum, pageSize);
        Page<Orders> orderPage = ordersService.page(page, new QueryWrapper<Orders>()
                .eq(customerId != null, "customer_id", customerId));

        return Result.success(orderPage);
    }


}